package chen.web.stat.keyword;

import java.net.URI;
import java.util.StringTokenizer;

class Helper {

	public static String getParameterValue(String url, String parameterName){
		int queryIndex = url.indexOf('?');
		if(queryIndex == -1 || queryIndex > url.length()+1){
			return null;
		}
		String queryString = url.substring(queryIndex+1);
		return getValueFromQueryString(queryString, parameterName);
	}
	
	public static String getValueFromQueryString(String queryString, String parameterName){
		StringTokenizer tokenizer = new StringTokenizer(queryString, "&");
		while(tokenizer.hasMoreTokens()){
			String token = tokenizer.nextToken();
			int index = token.indexOf('=');
			if(index != -1 && index != token.length()-1){
				String paramName = token.substring(0, index);
				String paramValue = token.substring(index+1);
				if(parameterName.equalsIgnoreCase(paramName)){
					return paramValue;
				}	
			}
		}
		return null;
	}
	
	public static boolean urlExtendsHost(String url, String host){
		if(url == null || host == null) return false;
		if(URI.create(url).getHost().equalsIgnoreCase(host)){
			return true;
		}
		return false;
	}
}
